package com.nervenets.general.annotation;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.google.common.collect.Lists;
import com.nervenets.general.Global;
import com.nervenets.general.utils.HttpTools;

import java.io.IOException;

public class JsonIgnoreEnvSerializer extends JsonSerializer<Object> implements ContextualSerializer {
    private String[] envs;

    public JsonIgnoreEnvSerializer() {
    }

    public JsonIgnoreEnvSerializer(String[] envs) {
        this.envs = envs;
    }

    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        String sessionEnv = (String) HttpTools.getHttpRequestAttribute(Global.Constants.SESSION_ENV);
        if (Lists.newArrayList(envs).contains(sessionEnv)) {
            jsonGenerator.writeNull();
        } else {
            jsonGenerator.writeObject(o);
        }
    }

    @Override
    public boolean isUnwrappingSerializer() {
        String sessionEnv = (String) HttpTools.getHttpRequestAttribute(Global.Constants.SESSION_ENV);
        return Lists.newArrayList(envs).contains(sessionEnv);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null) {
            JsonIgnoreEnv jsonIgnoreEnv = beanProperty.getAnnotation(JsonIgnoreEnv.class);
            if (jsonIgnoreEnv == null) {
                jsonIgnoreEnv = beanProperty.getContextAnnotation(JsonIgnoreEnv.class);
            }
            if (jsonIgnoreEnv != null) {
                return new JsonIgnoreEnvSerializer(jsonIgnoreEnv.value());
            }
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        return serializerProvider.findNullValueSerializer(null);
    }
}
